package com.zgs.mall.product.service.impl;

import com.alibaba.fastjson.TypeReference;
import com.zgs.common.constant.ProductConstant;
import com.zgs.common.to.SkuReductionTo;
import com.zgs.common.to.SpuBoundTo;
import com.zgs.common.to.es.SkuEsModel;
import com.zgs.common.utils.R;
import com.zgs.mall.product.entity.*;
import com.zgs.mall.product.feign.CouponFeignService;
import com.zgs.mall.product.feign.SearchFeignService;
import com.zgs.mall.product.feign.WareFeignService;
import com.zgs.mall.product.service.*;
import com.zgs.mall.product.vo.*;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zgs.common.utils.PageUtils;
import com.zgs.common.utils.Query;

import com.zgs.mall.product.dao.SpuInfoDao;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;


@Service("spuInfoService")
public class SpuInfoServiceImpl extends ServiceImpl<SpuInfoDao, SpuInfoEntity> implements SpuInfoService {

    @Autowired
    private SpuInfoDescService spuInfoDescService;
    @Autowired
    private SpuImagesService spuImagesService;
    @Autowired
    private ProductAttrValueService productAttrValueService;
    @Autowired
    AttrService attrService;
    @Autowired
    private SkuImagesService skuImagesService;
    @Autowired
    private SkuInfoService skuInfoService;
    @Autowired
    private SkuSaleAttrValueService skuSaleAttrValueService;
    @Autowired
    private CouponFeignService couponFeignService;
    @Autowired
    private BrandService brandService;
    @Autowired
    private CategoryService categoryService;
    @Autowired
    com.zgs.mall.product.feign.WareFeignService wareFeignService;
    @Autowired
    SearchFeignService searchFeignService;

    /**
     * 上传到es
     * @param spuId
     */
    @Transactional
    @Override
    public void spuUp(Long spuId) {
        List<SkuInfoEntity> skus =skuInfoService.queryBySpuId(spuId);
        List<Long> collect = skus.stream().map(SkuInfoEntity::getSkuId).collect(Collectors.toList());
        //TODO 发送远程 ,库存系统查询是否有库存
        Map<Long, Boolean>  skuHasStockMap=null;
        try{
            R skuhasStock = wareFeignService.getSkuhasStock(collect);

            List<SkuHasStockVo> skuHasStockVos = skuhasStock.getData( new TypeReference<List<SkuHasStockVo>>(){});
            skuHasStockMap = skuHasStockVos.stream().collect(Collectors.toMap(SkuHasStockVo::getSkuId, item -> item.getHasStock()));
        }catch (Exception e){
            log.error("远程调用出现异常,原因:{}",e);
        }
        final Map<Long, Boolean>  finalSkuHasStockMap=skuHasStockMap;
        //TODO 查询sku的所有可以被检索的规格属性信息 spu下都是一样的
        List<ProductAttrValueEntity> baseAttrs = productAttrValueService.list(new QueryWrapper<ProductAttrValueEntity>().eq("spu_id", spuId));
        List<Long> attrIds = baseAttrs.stream().map(attr -> {
            return attr.getAttrId();
        }).collect(Collectors.toList());
        //查询所有可检索的属性id
        List<Long> searchAttrIds=attrService.selectSearchAttrIds(attrIds);
        Set<Long> idSet= new HashSet<>(searchAttrIds);

        List<SkuEsModel.Attrs> attrs = baseAttrs.stream().filter(item -> {
            return idSet.contains(item.getAttrId());
        }).map(item -> {
            SkuEsModel.Attrs attrs1 = new SkuEsModel.Attrs();
            BeanUtils.copyProperties(item, attrs1);
            return attrs1;
        }).collect(Collectors.toList());
        //组装需要上传数据
        List<SkuEsModel> skuEsModels = skus.stream().map(sku -> {
            SkuEsModel skuEsModel = new SkuEsModel();
            Long skuId = sku.getSkuId();
            skuEsModel.setSkuId(skuId);
            skuEsModel.setSpuId(spuId);
            skuEsModel.setSkuTitle(sku.getSkuTitle());
            skuEsModel.setSkuPrice(sku.getPrice().toString());
            skuEsModel.setSaleCount(sku.getSaleCount());
            skuEsModel.setSkuImg(sku.getSkuDefaultImg());
            //查询库存表 hasStock hotScore
            //TODO 发送远程 ,库存系统查询是否有库存
            if(finalSkuHasStockMap==null){
                skuEsModel.setHasStock(true);
            }else{
                skuEsModel.setHasStock(finalSkuHasStockMap.get(sku.getSkuId()));
            }
            //TODO 热度评分
            skuEsModel.setHotScore(0L);//后台可控的复杂操作
            //TODO 查询品牌和分类的名字信息
            BrandEntity brandEntity = brandService.getById(sku.getBrandId());
            skuEsModel.setBrandId(sku.getBrandId());
            skuEsModel.setBrandName(brandEntity.getName());
            skuEsModel.setBrandImg(brandEntity.getLogo());
            CategoryEntity category = categoryService.getById(sku.getCatalogId());
            skuEsModel.setCatalogId(sku.getCatalogId());
            skuEsModel.setCatalogName(category.getName());
            //设置检索属性
            skuEsModel.setAttrs(attrs);
            return skuEsModel;
        }).collect(Collectors.toList());
        //TODO 远程发给es 进行上架
        R r = searchFeignService.productStatusUp(skuEsModels);
        if(r.getCode()==0){
            //调用成功
            //修改当前spu状态
            baseMapper.updateSpuStatus(spuId, ProductConstant.StatsEnum.SPU_UP.getCode());
        }else{
            //TODO 重复调用?接口幂等性:重试机制
        }
    }
    @Override
    public PageUtils queryPageByCondition(Map<String, Object> params) {
        QueryWrapper<SpuInfoEntity> queryWrapper = new QueryWrapper<>();
        String key = (String)params.get("key");
        if(!StringUtils.isEmpty(key)){
            queryWrapper.and((w)->{
                w.eq("id",key).or().like("spu_name",key);
            });
        }
        String status = (String)params.get("status");
        if(!StringUtils.isEmpty(status)&&!"0".equals(status)){
            queryWrapper.eq("publish_status",status);
        }
        String brandId = (String)params.get("brandId");
        if(!StringUtils.isEmpty(brandId)&&!"0".equals(brandId)){
            queryWrapper.eq("brand_id",brandId);
        }
        String catelogId = (String)params.get("catelogId");
        if(!StringUtils.isEmpty(catelogId)&&!"0".equals(catelogId)){
            queryWrapper.eq("catalog_id",catelogId);
        }


        IPage<SpuInfoEntity> page = this.page(
                new Query<SpuInfoEntity>().getPage(params),
                queryWrapper
        );

        return new PageUtils(page);
    }



    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<SpuInfoEntity> page = this.page(
                new Query<SpuInfoEntity>().getPage(params),
                new QueryWrapper<SpuInfoEntity>()
        );

        return new PageUtils(page);
    }

    @Transactional
    @Override
    public void saveSpuInfo(SpuSaveVo spuSaveVo) {
        //1保存 spu 基本信息 ， pms_spu_info
        SpuInfoEntity infoEntity = new SpuInfoEntity();
        BeanUtils.copyProperties(spuSaveVo, infoEntity);
        infoEntity.setCreateTime(new Date());
        infoEntity.setUpdateTime(new Date());
        this.saveBaseSpuInfo(infoEntity);
        //2 保存spu的描述图片 pms_spu_info_desc 商品介绍
        List<String> decript = spuSaveVo.getDecript();
        SpuInfoDescEntity spuInfoDescEntity = new SpuInfoDescEntity();
        spuInfoDescEntity.setSpuId(infoEntity.getId());
        spuInfoDescEntity.setDecript(String.join(",", decript));
        spuInfoDescService.savaSpuInfoDesc(spuInfoDescEntity);
        //3 保存spu图片集 pms_spu_images:spu图片集
        List<String> images = spuSaveVo.getImages();
        spuImagesService.saveImage(infoEntity.getId(), images);
        //4 spu的规格参数 pms_product_attr_value
        List<BaseAttrs> baseAttrs = spuSaveVo.getBaseAttrs();
        List<ProductAttrValueEntity> collect = baseAttrs.stream().map(attr -> {
            ProductAttrValueEntity valueEntity = new ProductAttrValueEntity();
            AttrEntity attrEntity = attrService.getById(attr.getAttrId());
            valueEntity.setAttrName(attrEntity.getAttrName());
            valueEntity.setAttrId(attr.getAttrId());
            valueEntity.setAttrValue(attr.getAttrValues());
            valueEntity.setSpuId(infoEntity.getId());
            return valueEntity;
        }).collect(Collectors.toList());
        productAttrValueService.saveBatch(collect);
        //5 spu的积分信息  mall_sms->sms_spu_bounds（spu积分表）
        Bounds bounds = spuSaveVo.getBounds();
        SpuBoundTo spuBoundTo = new SpuBoundTo();
        BeanUtils.copyProperties(bounds, spuBoundTo);
        spuBoundTo.setSpuId(infoEntity.getId());
        couponFeignService.save(spuBoundTo);

        //6 保存spu对应的sku信息
        //6.1 sku的基本信息  pms_sku_info
        List<Skus> skus = spuSaveVo.getSkus();
        if (skus != null && !skus.isEmpty()) {
            skus.forEach(item -> {
                List<Images> imagesList = item.getImages();
                String defaultImgUrl = "";
                for (Images images1 : imagesList) {
                    int defaultImg = images1.getDefaultImg();
                    if (defaultImg == 1) {
                        defaultImgUrl = images1.getImgUrl();
                        break;
                    }
                }
                SkuInfoEntity skuInfoEntity = new SkuInfoEntity();
                BeanUtils.copyProperties(item, skuInfoEntity);
                skuInfoEntity.setBrandId(infoEntity.getBrandId());
                skuInfoEntity.setCatalogId(infoEntity.getCatalogId());
                skuInfoEntity.setSaleCount(0L);
                skuInfoEntity.setSkuDefaultImg(defaultImgUrl);
                skuInfoEntity.setSpuId(infoEntity.getId());
                skuInfoService.saveSkuInfu(skuInfoEntity);
                Long skuId = skuInfoEntity.getSkuId();
                //6.2 sku的图片信息 pms_sku_images
                List<SkuImagesEntity> skuImagesList = imagesList.stream().
                        filter(images1 -> !StringUtils.isEmpty(images1.getImgUrl()))
                        .map(images1 -> {
                            SkuImagesEntity skuImagesEntity = new SkuImagesEntity();
                            skuImagesEntity.setSkuId(skuId);
                            skuImagesEntity.setDefaultImg(images1.getDefaultImg());
                            skuImagesEntity.setImgUrl(images1.getImgUrl());
                            return skuImagesEntity;
                        }).collect(Collectors.toList());
                skuImagesService.saveBatch(skuImagesList);
                //6.3 sku的销售属性信息 pms_sku_sale_attr_value
                List<Attr> attrs = item.getAttr();
                List<SkuSaleAttrValueEntity> collect1 = attrs.stream().map(attr -> {
                    SkuSaleAttrValueEntity skuSaleAttrValueEntity = new SkuSaleAttrValueEntity();
                    BeanUtils.copyProperties(attr, skuSaleAttrValueEntity);
                    skuSaleAttrValueEntity.setSkuId(skuId);
                    return skuSaleAttrValueEntity;
                }).collect(Collectors.toList());
                skuSaleAttrValueService.saveBatch(collect1);
                //6.4 sku 的优惠,满减等信息  mall_sms->sms_sku_ladder(打折表) sms_sku_full_reduction(满减表) sms_member_price 会员价表
                SkuReductionTo skuReductionTo = new SkuReductionTo();
                BeanUtils.copyProperties(item, skuReductionTo);
                skuReductionTo.setSkuId(skuId);
                R r = couponFeignService.savaInfo(skuReductionTo);
                if (r.getCode() != 0) {

                }
            });
        }

    }

    private void saveBaseSpuInfo(SpuInfoEntity infoEntity) {
        this.save(infoEntity);
    }

}